import { Controller } from 'egg';

// import axios from 'axios';

// import MD5 from 'md5.js';
const MD5 = require('md5.js')



export default class UserController extends Controller {

 

  public async login(){
        const {ctx}=this;

        const data:any = {}
        const {email,phone,password} = ctx.query;

        const {parseCookie} = ctx.service.mequest;

        data.password = new MD5().update(password).digest('hex');

        data.rememberLogin="true"
        email && (data.username = email);
        phone && (data.phone = phone);

        const url=`${this.config.baseUrl}/weapi/login${phone?'/cellphone':''}`

        const result:any = await this.service.mequest. createWebAPIRequest(url,'post',data,'');

        console.log('result',result.cookie)

        result. cookie && result.cookie.forEach(x =>x= x.replace('Domain=.music.163.com', ''))

         parseCookie(result.cookie).forEach(ck=>{
          ctx.cookies.set(ck.cookie.name,ck.cookie.value,ck.options)
        })

        ctx.body = result.body;



  }
  // 刷新登陆状态
  public async refresh(){



    const {parseCookie } = this.service.mequest;

    const url = `/weapi/login/token/refresh`;
    const data = {csrf_token: ""}

    let result:any  = await this.service.mequest. createWebAPIRequest(url,'POST',data);


    const {body,cookie} = result;
    
    cookie &&  parseCookie(cookie).forEach(ck=>{
      this.ctx.cookies.set(ck.cookie.name,ck.cookie.value,ck.options)
    })

    

    this.ctx.body = body;
    

  }

  public async status(){
    const {parseCookie} = this.ctx.service.mequest;

    const url = `/`;

    const result:any = await this.service.mequest.createWebAPIRequest(url,'GET',{});

    const {body,cookie} = result;
    
    cookie &&  parseCookie(cookie).forEach(ck=>{

      this.ctx.cookies.set(ck.cookie.name,ck.cookie.value,ck.options)
    })

      var _profile = /GUser\s*=\s*([^;]+);/.exec(body) 

      var _bindings = /GBinds\s*=\s*([^;]+);/.exec(body);


      let res:any = {};

      if(_profile){
          res.profile = eval(`(${_profile[1]})`)
          console.log(_profile[1])

      }
      if(_bindings){
          res.bindings = JSON.parse(_bindings[1])
          console.log(_bindings[1])
      }

    this.ctx.body = res
  }
}
// 9b2dc58df403165b14cfef7f45efc0e2
// 9b2dc58df403165b14cfef7f45efc0e2



